<?php

namespace App\Api\Eloquent;

use App\Admin\Eloquent\Message;
use DB;
use Log;
use Ibeibeili\SinaPay\Facades\CreateActivateMember;
use Ibeibeili\SinaPay\Facades\BindingVerify;
use App\Admin\Eloquent\GiftActivity;
use App\Admin\Eloquent\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Mockery\CountValidator\Exception;
use App\Admin\Eloquent\Information;


class User extends Model
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'scope', 'username', 'email', 'password', 'identity_id','phone_number','phone_number_verified','email_verified','last_login_at','make_mistake'
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * 获取关联的用户信息
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function userInfo()
    {
        return $this->hasOne('App\Api\Eloquent\UserInfo');
    }

    /**
     * 当前用户的所有角色
     */
    public function roles()
    {
        return $this->belongsToMany('App\Api\Eloquent\Role', 'role_user', 'user_id', 'role_id');
    }
    /**
     * 重写save()
     */
//    public function save(array $options = []){
//        if(!$this->exists){
//            $this->identity_id = $this->generateUniqueIdentutyId();
//        }
//
//        return parent::save($options);
//    }

    /**
     * 判断用户是否拥有指定角色
     *
     * @param  string|array $slug
     * @param  bool $requiredAll
     * @return bool
     *
     * 示例：
     *  $user->hasRole('user'); # true
     *  $user->hasRole('Agent'); # false
     *  $user->hasRole(['user', 'Agent']); # true
     *  $user->hasRole(['user', 'Agent'], true); # false
     */
    public function hasRole($slug, $requiredAll = false)
    {
        if (is_array($slug)) {
            foreach ($slug as $roleSlug) {
                $hasRole = $this->hasRole($roleSlug);

                if (!$requiredAll && $hasRole) {
                    return true;
                } elseif ($requiredAll && !$hasRole) {
                    return false;
                }
            }

            return $requiredAll;
        } else {
            foreach ($this->roles()->get() as $role) {
                if ($role->slug == $slug) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 范围查询只包括前台用户
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeFronts($query)
    {
        return $query->where('scope', 'front');
    }

    public static function paging_query(array $args, int $pagesize = 15)
    {
        $query = User::fronts()
            ->leftJoin('user_info as a', 'a.user_id', '=', 'users.id');

        //追加查询条件
        if (!empty($args['username']))
            $query = $query->where('users.username', 'like', '%' . $args['username'] . '%');

        if (!empty($args['name']))
            $query = $query->where('a.name', 'like', '%' . $args['name'] . '%');

        if (!empty($args['id_card']))
            $query = $query->where('a.id_card', 'like', '%' . $args['id_card'] . '%');

        if (!empty($args['phone']))
            $query = $query->where('a.phone', 'like', '%' . $args['phone'] . '%');

        return $query->paginate($pagesize);
    }


    /**
     * 获取保存在session中的前台用户对象
     *
     * @return mixed
     */
    public static function user()
    {
        return session(self::getFrontUserSessionKey());
    }

    /**
     * 将用户登出
     *
     * @param Request $request
     */
    public static function loginOut(Request $request)
    {
        $request->session()->remove(self::getFrontUserSessionKey());
    }

    /**注册完成动作
     * @param $data
     * @return mixed
     */
    public static function registerAction($data){
            $result['code']='900';
            $result['message']='注册成功';
            $user_info = null;
            $user = null;
        try{
            DB::beginTransaction();
//生成User
            $user['scope'] = 'front';//指定前台用户
            do {
                $user['identity_id'] =createSinaIdentityId();
            } while (User::where('identity_id', $user['identity_id'])->exists());

            $user['username'] = (!empty($data['username']))?$data['username']:null;//用户名
            $user['password'] = bcrypt($data['password']);//密码
            $user['phone_number'] =(!empty($data['phone_number']))?$data['phone_number']:null;//手机号码
            $user['phone_number_verified'] =0;//sina手机认证

            $user['email'] = null;
            $user['email_verified'] = 0;
            $user['remember_token'] = null;

            $do_user = new User($user);
            $do_user->save();
//生成UserInfo
            $user_info['org_code']=config('p2pdefault.user.organizational_code');
            $user_info['dept_code']=config('p2pdefault.user.dept_code');
            $user_info['broker_code']=config('p2pdefault.user.broker_code');
            if (!empty($data['recommended'])) {
                    $recommended_role=User::where('id','=',$data['recommended']->user_id)->first()->hasRole('Agent');
                    if($recommended_role){
                        //发放站内信
                        $content_text =date('Y-m-d H:i:s').'，您的客户 ['.$user['phone_number'].'],成功注册!';
                        Message::sendMessage('sys_msg','客户注册通知-'.$user['phone_number'],$content_text,$data['recommended']->user_id);
                        $user_info['org_code']=$data['recommended']->org_code;
                        $user_info['dept_code']=$data['recommended']->dept_code;
                        $user_info['broker_code']=$data['recommended']->invite_code;
                    }
                    elseif($data['recommended']->invite_code==$data['recommended']->second_broker_code){
                        //向一级经济人发放站内信
                        $first_agent=UserInfo::where('invite_code','=',$data['recommended']->broker_code)->first();
                        $second_agent=User::where('id','=',$data['recommended']->user_id)->first();
                        $second_agent_name=!empty($second_agent->userInfo->name)?$second_agent->userInfo->name :(!empty($second_agent->phone_number)?$second_agent->phone_number:$second_agent->username);
                        $content_text =date('Y-m-d H:i:s').'，您的二级经纪人'.$second_agent_name.'的客户 ['.$user['phone_number'].'],成功注册!';
                        Message::sendMessage('sys_msg','客户注册通知-'.$user['phone_number'],$content_text,$first_agent->user_id);
                        $user_info['org_code']=$data['recommended']->org_code;
                        $user_info['dept_code']=$data['recommended']->dept_code;
                        $user_info['broker_code']=$data['recommended']->broker_code;
                        $user_info['second_broker_code']=$data['recommended']->invite_code;
                    }
                    else{
                        //发放推荐红包
                        $invite_gift=new GiftActivity();
                        $invite_result=$invite_gift->sendGift('gift_grant_rule_5',$data['recommended']->user_id);
                        $invite_result['status']==0 && $user_info['invite_money']=$invite_result['data']['money'];
                        $user_info['recommended']=$data['recommended']->user_id;
                    }
            }
            //生成推荐码
            do {
                $user_info['invite_code'] = create_code(6);
            } while (UserInfo::where('invite_code', $user_info['invite_code'])->exists());
            if($data['second_agent']){
                if(!empty($data['recommended'])){
                    if($recommended_role){
                        $user_info['second_broker_code']=$user_info['invite_code'];
                    }
                }
            }
            $user_info['user_id'] = $do_user->id;
            //添加用户详细信息
            $do_user_info = new UserInfo($user_info);
            //chunmeng.jiang@live.com start
            if($data['activity']){
                $do_user_info->activity_register=1;
            }

            // if(isset($user_info['recommended']) && !empty($user_info['recommended']))
            //     $do_user_info->recommended = $user_info['recommended'];
            //chunmeng.jiang@live.com end
            $do_user_info->save();
//生成UserRole
            $role=Role::where('slug','=','User')
                ->first();
            if($role){
                //存角色用户关系
                RoleUser::insert(['role_id'=>$role->id,'user_id'=>$do_user->id]);
            }
            else{
                throw new Exception('用户角色不存在',600);//普通用户角色不存在
            }
//发放注册红包
            $gift=new GiftActivity();
            $register_gift_result=$gift->sendGift('gift_grant_rule_1',$do_user->id);
            if($register_gift_result['status']==0){
                Cache::forever('api'.$user['phone_number'],$register_gift_result['money']);
            }
            $user_result = CreateActivateMember::send(['identity_id' => $user['identity_id'], 'identity_type' => 'UID']);
            if ($user_result['response_code'] != 'APPLY_SUCCESS') {
                throw new Exception($user_result['response_message'],600);//sina注册会员失败
            }
            //如果有手机号码则发起新浪认证
            if($user['phone_number']){
//                $to_user=User::where('phone_number',$user['phone_number'])->first();
//                if($to_user){
//                    throw new Exception('手机号已被注册','102');
//                }
//                else{
                $Mobile_result=BindingVerify::send(['identity_id'=>$user['identity_id'],'verify_type'=>'MOBILE','verify_entity'=>$user['phone_number']]);
                if($Mobile_result['response_code']!='APPLY_SUCCESS'){
                    throw new Exception($Mobile_result['response_message'],600);//手机认证失败
                }
//                }
                $do_user->phone_number_verified =1;//sina手机认证
                $do_user->save();
            }
            User::loginIn($do_user);
            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            $result['code']=$e->getCode();
            $result['message']=$e->getMessage();
            return $result;
        }
        return  $result;
    }
    /**
     * 用户登陆
     *
     * @param Request $request
     * @param User $user
     */
    public static function loginIn(User $user)
    {
        //去除密码

        $user->__unset('password');
//        $request->session()->put(self::getFrontUserSessionKey(), $user);
//        $request->session()->save();
        session([self::getFrontUserSessionKey()=>$user]);
    }

    /**
     *
     * 根据用户名和密码检索用户(用户名 邮箱 或者手机号 and 密码)
     *
     * @param array $credentials
     * @return bool|null
     */
    public static function retieveByCredentials(array $credentials)
    {
        $u = null;
        $username = $credentials['username'];
        $password = $credentials['password'];

        //查询用户名
        $users = User::where('username', $username)
            ->orWhere('email', $username)
            ->orWhere('phone_number', $username)
            ->get();

        if (count($users) == 0) {
            return false;
        }

        foreach ($users as $user) {
            if (Hash::check($password, $user->password)) {
                $u = $user;
            }
        }

        if ($u != null) {
            return $u;
        }

        return false;
    }
    //根据用户名获取用户对象
    public static function toUser($username){
        //查询用户名
        $users = User::where('username', $username)
            ->orWhere('email', $username)
            ->orWhere('phone_number', $username)
            ->first();
        return $users;
    }

    /**
     * 判断用户是否登陆
     * @param Request $request
     * @return bool
     */
    public static function isLogin(Request $request)
    {
        return empty($request->session()->has(self::getFrontUserSessionKey())) ? false : true;
    }

    public static function getFrontUserSessionKey()
    {
//        return config('session.front_login_user');
        return 'api_front_user';
    }

    /**
     * 给用户发送邮件
     */
    public function sendEmailBindLink(string $email)
    {
        //生成随机验证码
        $code =rand(100000, 999999);

        //邮件内容模板
        $information = Information::where('type', 'information_email')
            ->where('position', 'email_validate_code')
            ->where('state', 1)
            ->first();
        $username = empty($this->userInfo->name) ? $this->username : $this->userInfo->name;
        //生成验证url
        $link = "http://".$_SERVER['SERVER_NAME'].'/api_user/'.$this->id.'/emailvalidate'.'/'.md5($code);
        //替换模板内容
        $content = str_replace('{user}', $username, $information->content);
        $content = str_replace('{link}', $link, $content);

        $fa_data['content']=$content;
        $fa_data['email']=$email;
        $fa_data['title']=$information->title;
//        $email = $email;
//        $title = $information->title;

        $data['code']=$code;
        $data['email']=$email;
        if(sendEmail($fa_data)){
            Cache::put(('api_uid_'.$this->id.'_email_validate'),$data,30);
            return true;
        }
        return false;
    }

    /**验证邮箱
     * @param $id
     * @param $code
     */
    public function verifyEmail($id,$code){
        $r_result=true;
        try {
            DB::beginTransaction();
            $data=Cache:: pull(('uid_'.$id.'_email_validate'));
            md5($data['code'])==$code or abort('600');
            $user=User::findOrFail($id);
            $user->email=$data['email'];
            $user->save();
            $result=BindingVerify::send(['identity_id'=>$user->identity_id,'verify_type'=>'EMAIL','verify_entity'=>$data['email']]);
            $result['response_code']=='APPLY_SUCCESS' or abort('600');
            DB::commit();
        }catch(Exception $e) {
            DB::rollback();
            $r_result=false;
        }
        return $r_result;
    }

//    protected function generateUniqueIdentutyId()
//    {
//        do {
//            $user['identity_id'] = createSinaIdentityId();
//        } while (User::where('identity_id', $user['identity_id'])->exists());
//    }
}